package com.guxiuwei.sys.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guxiuwei.sys.common.Result;
import com.guxiuwei.sys.entity.Leaves;
import com.guxiuwei.sys.entity.Spareparts;
import com.guxiuwei.sys.entity.User;
import com.guxiuwei.sys.entity.Worder;
import com.guxiuwei.sys.mapper.LeavesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 谷秀伟
 * @since 2023-03-17
 */
@RestController
    @RequestMapping("/sys/leaves")
public class LeavesController {

    @Autowired
    private LeavesMapper leavesMapper;

    //获取前端传入的默认显示页码，页面容量数，
    // 和搜索框查询条件，对数据库中请假记录信息表进行分页查询
    @GetMapping("/selectAll")
    public Result<?> findPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "") String search ){
        QueryWrapper<Leaves> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("lid");
        if (StrUtil.isNotBlank(search)){
            wrapper.like("name",search);
        }
        Page<Leaves> leavesPage = leavesMapper.selectPage(new Page<>(pageNum, pageSize),wrapper );
        System.out.println(leavesPage);
        return Result.success(leavesPage);
    }

    //将leaves对象存入数据库中，并判断记录是否已经存在，设置新记录状态为待审批
    @PostMapping("/add")
    public Result<?> save(@RequestBody Leaves leaves){
        QueryWrapper<Leaves> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("lid")
                .last("limit 1");
        Leaves leave = leavesMapper.selectOne(queryWrapper);
        Leaves res = leavesMapper.selectOne(Wrappers.<Leaves>lambdaQuery().eq(Leaves::getLid, leaves.getLid()));
        if (res != null){
            return Result.error("0","该请假单已注册");
        } else {
            leaves.setStatus("待审批");
            leaves.setLid(leave.getLid() + 1);
            leavesMapper.insert(leaves);
            return Result.success();
        }
    }

    //对前端传入的leaves对象进行修改更新操作
    @PutMapping("/update")
    public Result<?> update(@RequestBody Leaves leaves){
        leavesMapper.updateById(leaves);
        return Result.success();
    }

    //权限（现场组） 对前端传入的leaves对象的lid进行相关记录删除操作
    @DeleteMapping("/delete/{lid}")
    public Result<?> delete(@PathVariable Long lid){
        leavesMapper.deleteById(lid);
        return Result.success();
    }

    //得到待审批请假申请数量 返回给管理者
    @GetMapping("/countStatus")
    public Result<?> countStatus(){
        QueryWrapper<Leaves> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status","待审批");
        int count = leavesMapper.selectCount(queryWrapper);
        return Result.success(count);
    }

    //对前端传入的leaves对象的lid进行相关记录审批
    @PutMapping("/finish")
    @PreAuthorize("hasAuthority('云平台维护室')")
    public Result<?> finish(@RequestBody Leaves leaves){
        leaves.setStatus("已完成");

        leavesMapper.updateById(leaves);
        return Result.success();
    }

    //上传接口
    @PostMapping("fileUpload")
    public Result<?> fileUpload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename(); //获取源文件名称
        String flag = IdUtil.fastSimpleUUID();
        String filePath = System.getProperty("user.dir") + "/src/main/resources/static/leavesImg/" + flag + "_" + filename; //获取上传的路径
        FileUtil.writeBytes(file.getBytes(),filePath);//把文件写入到上传路径
        return Result.success("http://localhost:8080/api/sys/leaves/getFiles/" + flag);//返回结果
    }

    //下载接口

    @GetMapping("/getFiles/{flag}")
    public void getFiles(HttpServletResponse response, @PathVariable String flag){
        OutputStream os; //输出流对象
        String filePath = System.getProperty("user.dir") + "/src/main/resources/static/leavesImg/"; //定义文件上传的根路径
        List<String> listFile = FileUtil.listFileNames(filePath); //获取所有文件名称
        String fileName = listFile.stream().filter(name -> name.contains(flag)).findAny().orElse(""); //找到和参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)){
                response.reset();
                response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + fileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }

    }

}

